import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import {bbox} from 'ol/loadingstrategy';

import GlayerIndex from './GlayerIndex';
import Gstyle from './Gstyle';
import {Heatmap as HeatmapLayer} from "ol/layer";
import {tile as tileStrategy} from "ol/loadingstrategy";
import {createXYZ} from "ol/tilegrid";
import EsriJSON from "ol/format/EsriJSON";
import {ImageArcGISRest, TileArcGISRest} from "ol/source";
import {Image as ImageLayer,Tile as TileLayer} from "ol/layer";

class Glayers {
  constructor() {
    this.defaultPoint = new VectorLayer({
      source: new VectorSource({
        format: new GeoJSON(),
      }),
      style: Gstyle.feature_default,
      zIndex: GlayerIndex.POINT,
      visible: true,
      id: 'defaultPoint'
    });
    this.station = new VectorLayer({
      source: new VectorSource({
        format: new GeoJSON(),
      }),
      style: Gstyle.station,
      zIndex: GlayerIndex.POINT,
      visible: true,
      id: 'station'
    });
    this.line = new VectorLayer({
      source: new VectorSource({
        format: new GeoJSON(),
      }),
      style: Gstyle.line,
      zIndex: GlayerIndex.LINE,
      visible: true,
      id: 'line'
    });
    this.event_heatmap = new HeatmapLayer({
      source: new VectorSource({
        format: new GeoJSON(),
      }),
      radius: 10,
      blur: 20,
      gradient: ['#0f0', '#ff0', '#f00'],
      zIndex: GlayerIndex.POINT,
      visible: false,
      id: 'heatmap',
      weight: function(feature) {
        const count = Number(feature.get('count') == 0 ? Math.floor((Math.random()*1000)+1) : feature.get('count'));
        // console.log(count);
        return count;
      },
    });
  }
  //图层加载  要素服务
  addVectorLayer = (url,dispatch,where,layerType,epsG4326Projection,description,callback) =>  {
    var esrijsonFormat = new EsriJSON();
    var vectorSource = new VectorSource({
      loader: function(extent, resolution, projection) {
        dispatch({
          type: url,
          payload: {
            where: where,
            type: layerType,
            returnGeometry: true,
            spatialRel: 'esriSpatialRelIntersects',
            geometry: '{"xmin":' + extent[0] + ',"ymin":' +
              extent[1] + ',"xmax":' + extent[2] + ',"ymax":' + extent[3] +
              ',"spatialReference":{"wkid":4326}}',
            // geometryType: 'esriGeometryPoint',
            inSR: epsG4326Projection,
            outFields: '*',
            outSR: epsG4326Projection
          },
        }).then(response => {
          if (response.error) {
            console.log('服务==>>'+ response.error.message + '\n' +
              response.error.details.join('\n'));
          } else {
            // dataProjection will be read from document
            var features = esrijsonFormat.readFeatures(response, {
              featureProjection: projection
            });
            if (features.length > 0) {
              vectorSource.addFeatures(features);
            }
          }
          if (callback){
            callback();
          }
        });
      },
      strategy: bbox
    });

    //图层加载  此源类型支持地图和图像服务
    //   addVectorLayer = (url,dispatch,where,layerType,epsG4326Projection) =>  {
    //    var vector = new TileLayer({
    //       extent: [-13884991, 2870341, -7455066, 6338219],
    //       source: new TileArcGISRest({
    //         url: url
    //       })
    //     });
    //   return vector;
    // }
    var vector = null;
    // if (layerType.indexOf('poi')!=-1){
    //    vector = new VectorLayer({
    //     zIndex: 100,
    //     source: vectorSource,
    //   });
    // }else {
      vector = new VectorLayer({
        zIndex: 100,
        source: vectorSource,
        style: function(feature) {
          var geometryType =  feature.getGeometry().getType();
          var classify = layerType.substr(layerType.lastIndexOf('/')+1);
          if(geometryType=='Point'){
            return Gstyle.styleCacheIndexPoint(description,classify);
          }else if(geometryType=='LineString'){
            return Gstyle.styleCacheIndexLineString(description,classify);
          }else if(geometryType=='Polygon' || geometryType=='MultiPolygon'){
            return Gstyle.styleCacheIndexPolygon(description,classify);
          }else {
            return Gstyle.styleCacheIndexLineString(description,classify);
          }
        }
      });
    // }
    return vector;
  }
  //获取vectorSource
  queryVectorSource = (url,dispatch,where,layerType,epsG4326Projection) =>  {
    var esrijsonFormat = new EsriJSON();
    var vectorSource = new VectorSource({
      loader: function(extent, resolution, projection) {
        dispatch({
          type: url,
          payload: {
            where: where,
            type: layerType,
            returnGeometry:true,
            spatialRel: 'esriSpatialRelIntersects',
            // geometry: '{"xmin":' + extent[0] + ',"ymin":' +
            //   extent[1] + ',"xmax":' + extent[2] + ',"ymax":' + extent[3] +
            //   ',"spatialReference":{"wkid":4326}}',
            inSR: epsG4326Projection,
            outFields: '*',
            outSR: epsG4326Projection
          },
        }).then(response => {
          if (response.error) {
            console.log('服务==>>'+response.error.message + '\n' +
              response.error.details.join('\n'));
          } else {
            // dataProjection will be read from document
            var features = esrijsonFormat.readFeatures(response, {
              featureProjection: projection
            });
            if (features.length > 0) {
              vectorSource.addFeatures(features);
            }
          }
        });
      },
      strategy: tileStrategy(createXYZ({
        tileSize: 512 * 10
      }))
    });
    return vectorSource;
  }
  //栅格图层
  gridLayer = (url,tableId,callback) => {
    var layer = new TileLayer({
      source: new TileArcGISRest({
        url: url,
        cacheSize: 2048,
        params: {
          DPI: 50,
        }
      }),
      id: 'base',
      zIndex: GlayerIndex.BASE
    });
    callback(layer);
  }
}
export default Glayers;
